//
//  FLLCycleImage.m
//  FLLGodOfCooking
//
//  Created by LL.F on 16/9/2.
//  Copyright © 2016年 LL.F. All rights reserved.
//

#import "FLLCycleImage.h"
#import "FLLMacro.h"
#import "UIImageView+WebCache.h"
#import "ZWYNetTool.h"

@interface FLLCycleImage ()<UICollectionViewDataSource, UICollectionViewDelegate>
@property (nonatomic, strong) UICollectionView *cycleCollectionView;
@property (nonatomic, strong) UICollectionViewFlowLayout *layout;
@property (nonatomic, strong) UIPageControl *pageControl;
@property (nonatomic, strong) NSTimer *timer;
@end

@implementation FLLCycleImage
- (instancetype)initWithFrame:(CGRect)frame {
    self = [super initWithFrame:frame];
    if (self) {
        self.backgroundColor = [UIColor redColor];
        [self setUp];
    }
    return self;
}
- (instancetype)initWithCoder:(NSCoder *)aDecoder {
    self = [super initWithCoder:aDecoder];
    if (self) {
        self.backgroundColor = [UIColor redColor];
        [self setUp];
    }
    return self;
}

- (void)setUp {
    [self createCollectionView];
    [self createPageControl];
    [self createTimer];
}
- (void)createCollectionView {
    _layout = [[UICollectionViewFlowLayout alloc] init];
    _layout.scrollDirection = UICollectionViewScrollDirectionHorizontal;
    _layout.minimumLineSpacing = 0;
    _layout.minimumInteritemSpacing = 0;
    _cycleCollectionView = [[UICollectionView alloc] initWithFrame:CGRectZero collectionViewLayout: _layout];
    _cycleCollectionView.delegate = self;
    _cycleCollectionView.dataSource = self;
    _cycleCollectionView.pagingEnabled = YES;
    
    [_cycleCollectionView registerClass:[FLLCycleImageCell class] forCellWithReuseIdentifier:@"cycleCollectionViewCell"];
    
    _cycleCollectionView.showsHorizontalScrollIndicator = NO;
    [self addSubview:_cycleCollectionView];
    _cycleCollectionView.backgroundColor = [UIColor whiteColor];
}
- (void)setMainImageArray:(NSMutableArray<Banner *> *)mainImageArray
{
    _mainImageArray = mainImageArray;
    id first = _mainImageArray.firstObject;
    id last = _mainImageArray.lastObject;
    [_mainImageArray addObject:first];
    [_mainImageArray insertObject:last atIndex:0];
    [_cycleCollectionView reloadData];
}

#pragma mark - CollectionView Datasource
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section {
    _pageControl.numberOfPages = _mainImageArray.count - 2;
    return _mainImageArray.count;
}
- (__kindof UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {
    
    FLLCycleImageCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"cycleCollectionViewCell" forIndexPath:indexPath];
    // 网络请求图片
    [cell.cycleImage sd_setImageWithURL:[NSURL URLWithString:self.mainImageArray[indexPath.row].banner_picture] completed:^(UIImage *image, NSError *error, SDImageCacheType cacheType, NSURL *imageURL) {
    }];
       
    // 本地图片
    //    cell.cycleImage.image = [UIImage imageNamed:_array[indexPath.row]];
    
    return cell;
}
#pragma mark - CreatePageControl
- (void)createPageControl {
    self.pageControl = [[UIPageControl alloc] initWithFrame:CGRectZero];
    _pageControl.currentPageIndicatorTintColor = FLLOrangeColor;
    _pageControl.pageIndicatorTintColor = [UIColor lightGrayColor];
    
    [self addSubview:_pageControl];
    
}
#pragma mark - CreateTimer
- (void)createTimer {
    // 这个创建NSTimer的方式仅仅是创建, 并没有加在runLoop中, 所以需要手动加入RunLoop中
    //    NSTimer *timer = [NSTimer timerWithTimeInterval:2.0 target:self selector:@selector(nextPage) userInfo:nil repeats:YES];
    
    //    [[NSRunLoop mainRunLoop] addTimer:timer forMode:NSRunLoopCommonModes];
    // 创建一个timer, 并添加到loop中
    // NSRunLoopCommonModes 和NSDefaultRunLoopMode
    // 后者代表默认状态, scheduledTimerWithTimeInterval添加默认状态
    // 前者为多种状态, 包含默认 及 滚动
    NSTimer *timer = [NSTimer scheduledTimerWithTimeInterval:3.0 target:self selector:@selector(nextPage) userInfo:nil repeats:YES];
    self.timer = timer;
    
}
#pragma mark - CreateView
- (void)nextPage {
    CGFloat totaloffset = _cycleCollectionView.contentOffset.x + self.bounds.size.width;
    [_cycleCollectionView setContentOffset:CGPointMake(totaloffset, 0) animated:YES];
    if (totaloffset == (_mainImageArray.count - 1) * self.bounds.size.width) {
        _cycleCollectionView.contentOffset = CGPointZero;
    }
    _pageControl.currentPage = (_cycleCollectionView.contentOffset.x + self.bounds.size.width) / self.bounds.size.width - 1;
}
- (void)removeTimer {
    // 取消timer
    [self.timer invalidate];
    self.timer = nil;
}
- (void)layoutSubviews {
    [super layoutSubviews];
    _cycleCollectionView.frame = self.bounds;
    _layout.itemSize = self.bounds.size;
    [_cycleCollectionView setContentOffset:CGPointMake(SCREEN_WIDTH, 0)];
    
    _pageControl.frame = CGRectMake(0, 0, 100, 20);
    _pageControl.center = CGPointMake(SCREEN_WIDTH - 50, self.bounds.size.height - 20);

    
}
- (void)scrollViewWillBeginDragging:(UIScrollView *)scrollView {
    [self removeTimer];
}
- (void)scrollViewDidEndDragging:(UIScrollView *)scrollView willDecelerate:(BOOL)decelerate {
    [self createTimer];
}
- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView {
    //#warning 直接判断等与0有啥问题
    if (scrollView.contentOffset.x <= _cycleCollectionView.bounds.size.width / 2.0) {
        [_cycleCollectionView scrollToItemAtIndexPath:[NSIndexPath indexPathForItem:(_mainImageArray.count - 2) inSection:0] atScrollPosition:UICollectionViewScrollPositionNone animated:NO];
    } else if (scrollView.contentOffset.x >= _cycleCollectionView.bounds.size.width * (_mainImageArray.count - 1) - 1) {
        [_cycleCollectionView scrollToItemAtIndexPath:[NSIndexPath indexPathForItem:1 inSection:0] atScrollPosition:UICollectionViewScrollPositionNone animated:NO];
    }
    _pageControl.currentPage = scrollView.contentOffset.x / _cycleCollectionView.bounds.size.width - 1;
    
}

@end
#pragma mark - CollectionViewCell
@implementation FLLCycleImageCell

- (instancetype)initWithFrame:(CGRect)frame {
    self = [super initWithFrame:frame];
    if (self) {
        self.cycleImage = [[UIImageView alloc] initWithFrame:self.bounds];
        [self.contentView addSubview:_cycleImage];
           }
    return self;
}
- (void)layoutSubviews {
    [super layoutSubviews];
    
}

@end
